import { Data } from '@node_modules/@angular/router/src/config';
import { element } from 'protractor';
import { AssignmentDisplayOutput, BomAnalyseServiceProxy, CommonServiceProxy, DefaultArrangementInput, GetDashboardDataOutput, HandManageInput, MatingDetaillist, MatingManagerServiceProxy, MatingTreeGridDto, OperationLogDto, OrganizationUnitDto, OrganizationUnitUserListDto, PartsOutboundInput, ProcessLineDto, ProcessNodeDto } from './../../../shared/service-proxies/service-proxies';
import { Component, Injector, ViewChild } from '@angular/core';
import { LazyLoadEvent } from 'primeng/components/common/lazyloadevent';
import { MessageService } from '@abp/message/message.service';
import { Table } from 'primeng/components/table/table';
import { Paginator } from 'primeng/components/paginator/paginator';
import { InspectionHandleServiceProxy, InspectionFileCommonServiceServiceProxy, InspectionSeverityDescOutDto, InspectionStandardDescDto, CodeFormatDescServiceProxy, OperationHistoryServiceProxy, InspectionTypeDescDto, InspectionFileUploadDto, ProductionAssignmentServiceProxy, ProductionDesignServiceProxy, AssignmentTreeOutput } from '@shared/service-proxies/service-proxies';
import { finalize } from 'rxjs/operators';
import { AppComponentBase } from '@shared/common/app-component-base';
import { AppSessionService } from '@shared/common/session/app-session.service';
import { TreeNode } from 'primeng/api';
import * as go from "gojs";
import { FileDownloadService } from '@shared/utils/file-download.service';

@Component({
    selector: 'app-process-matching',
    templateUrl: './process-matching.component.html',
    styleUrls: ['./process-matching.component.less']
})
export class ProcessMatchingComponent extends AppComponentBase {
    @ViewChild('paginator') paginator: Paginator;
    @ViewChild('dataTable') dataTable: Table;
    modelList: any[];
    lotNoList: any[];
    childNodes: any;
    productionPlan: AssignmentDisplayOutput;
    processLineList: ProcessLineDto[];//芯及路线
    processNodeList: ProcessNodeDto[];
    diagram = undefined; // 路线图
    nodeDataArray = []; // 节点数据
    linkDataArray = []; // 线数据
    handelInfo = new HandManageInput();
    logList: OperationLogDto[];
    getOrganizationUnitList: OrganizationUnitDto[];
    getOrganizationUnitUsersByIdList: OrganizationUnitUserListDto[];
    tableList: any = {
        matingTreeGridList: [],
    };
    detailInfo: any = {
        info: undefined,
        list: []
    }
    detailVisible: boolean = false
    selectNode: any
    constructor(
        injector: Injector,
        private _messageService: MessageService,
        private _inspectionHandleServiceProxy: InspectionHandleServiceProxy,
        private _codeFormatDescServiceProxy: CodeFormatDescServiceProxy,
        private _operationHistoryServiceProxy: OperationHistoryServiceProxy,
        private _inspectionFileCommonServiceServiceProxy: InspectionFileCommonServiceServiceProxy,
        private _user: AppSessionService,
        private _productionAssignmentServiceProxy: ProductionAssignmentServiceProxy,
        private _productionDesignServiceProxy: ProductionDesignServiceProxy,
        private _matingManagerServiceProxy: MatingManagerServiceProxy,
        private _fileDownloadService: FileDownloadService,
        private _bomAnalyseServiceProxy: BomAnalyseServiceProxy,
        private _commonServiceProxy: CommonServiceProxy,
    ) {
        super(injector);
        this.data2 = [{
            label: 'F.C Barcelona',
            expanded: true,
            children: [
                {
                    label: 'F.C Barcelona',
                    expanded: true,
                    children: [
                        {
                            label: 'Chelsea FC'
                        },
                        {
                            label: 'F.C. Barcelona'
                        }
                    ]
                },
                {
                    label: 'Real Madrid',
                    expanded: true,
                    children: [
                        {
                            label: 'Bayern Munich'
                        },
                        {
                            label: 'Real Madrid'
                        }
                    ]
                }
            ]
        }];
    }
    files2: AssignmentTreeOutput[] = [];
    selectedFiles1: AssignmentTreeOutput;
    tasklist: any = [];//任务编号列表
    queryInfo = {
        model: undefined,
        lotNo: undefined,
    };//查询条件
    typeDescList: any[];//一级异常下拉
    rangeDates: string;//统计时间
    dialogType: string = '新增'
    addVisible: boolean = false;//弹窗 参数
    llVisible: boolean = false;//履历 参数
    defaultVisible: boolean = false;//默认排配计划 参数
    defaultInfo = new DefaultArrangementInput()
    // addInfoUi = new HandManageInput();//修改集合
    addInfoUi: any = {
        startTime: "",
    };//修改集合
    formatDropList: any[];//编码规则 列表
    severityDescList: InspectionSeverityDescOutDto[];//等级下拉
    userList: any[];//处理人 提报人下拉
    savingAddDia: boolean = false;//禁止频繁保存操作
    itemInfoList: any[];//二级异常下拉
    data2: TreeNode[];
    selectRow: any = [];
    goGo = go.GraphObject.make;
    shortageVisible: boolean = false
    rengongSelect: any = []
    cols: any[];
    saveFlag = true;
    ngOnInit() {
        this.getmodelList()
        this.getDesigenTree()
        this.diagram = this.goGo(go.Diagram, "myDiagramDiv");
        this.getOrganizationUnit()
        this.cols = [
            { field: 'name', header: 'Name' },
            { field: 'size', header: 'Size' },
            { field: 'type', header: 'Type' }
        ];
    }
    // 获取班组
    getOrganizationUnit() {
        this._productionAssignmentServiceProxy.getOrganizationUnit(
        )
            .pipe(finalize(() => { }))
            .subscribe(result => {
                this.getOrganizationUnitList = result
            });
    }
    // 全选
    selectedCars3All(): void {
        this.selectRow = []
        for (let index = 0; index < this.tableList.matingTreeGridList.length; index++) {
            const element = this.tableList.matingTreeGridList[index];
            if (element.children.length != 0) {
                this.selectRow.push(element)
            }
        }
        for (let index = 0; index < this.selectRow.length - 1; index++) {
            const element = this.selectRow[index];
            if (element.children) {
                element.children.forEach(item => {
                    this.selectRow.push(item)
                });
            }

        }
    }
    //班组 change事件
    unitChangeEv(ev) {
        let idArr = []
        ev.forEach(element => {
            idArr.push(element.id)
        });
        this.getOrganizationUnitUsersById(idArr)
    }
    // 获取装配人员n
    getOrganizationUnitUsersById(organizationIdList) {
        this._productionAssignmentServiceProxy.getOrganizationUnitUsersById(
            organizationIdList
        )
            .pipe(finalize(() => { }))
            .subscribe(result => {
                this.getOrganizationUnitUsersByIdList = result
            });
    }
    //型号下拉
    getmodelList() {
        this._commonServiceProxy.getModelList()
            .pipe(finalize(() => { }))
            .subscribe(result => {
                this.modelList = result
            });
    }
    /**
     * 发次
       lotstr — (optional)
       model — (optional)
     */

    getLotNoList(event): any {
        this._commonServiceProxy.getLotNoList(

            this.queryInfo.model.value
        )
            .pipe(finalize(() => { }))
            .subscribe(result => {
                this.lotNoList = result
            });
    }
    // 组合为需要的数据格式
    setSelectProps(val) {
        return {
            label: val,
            value: val
        }
    }
    /**
     根据型号与发次查询树结构
     * //  model — (optional)
      //lotNo — (optional)
     */
    getDesigenTree() {
        this._productionDesignServiceProxy.getProductionDesigenTree(
            this.queryInfo.model ? this.queryInfo.model.value : undefined,
            this.queryInfo.lotNo ? this.queryInfo.lotNo.value : undefined,
        )
            .pipe(finalize(() => { }))
            .subscribe(result => {
                if (result.id == undefined) {
                    this.files2 = [];
                    return
                }
                let arr: AssignmentTreeOutput[] = []
                arr.push(result)
                this.files2 = this.isEqual(JSON.parse(JSON.stringify(arr)))
                this.expandAllTree();
            });
    }
    expandAllTree() {
        this.files2.forEach((node) => {
            this.expandRecursive(node, true);
        });
    }
    private expandRecursive(node: any, isExpand: boolean) {
        node.expanded = isExpand;
        if (node.children) {
            node.children.forEach((childNode) => {
                this.expandRecursive(childNode, isExpand);
            });
        }
    }
    // 组合树结构数据
    isEqual(obj1) {
        for (const iterator of obj1) {
            iterator.label = iterator.nodeName
            // iterator.expandedIcon = "pi pi-folder-open"
            // iterator.collapsedIcon = "pi pi-folder"
            if (iterator.treeList) {
                iterator.children = iterator.treeList
                this.isEqual(iterator.treeList)
            }
        }
        return obj1
    }
    //点击树节点
    nodeSelect(event): void {
        /// id Id
        /// 节点名称  NodeName
        /// 图号 NodeDrawingNo
        /// 是否关联 IsRelation
        /// 父ID  ParentId
        /// 层级 NodeLevel  8工序   9工步
        /// 父节点Code  ParentCode
        /// 节点Code NodeCode
        /// 是否叶节点 IsLeaf
        /// 是否导出 IsExport
        this.getNodePlanDetails(event.node.id)
        this.selectNode = event.node
        this.selectRow = []
        if (event.node.isRelation === 1) {//树结构判断是否有子节点
            event.node.children = []
            event.node.treeList = []
            this.getProductionTechquine(event.node.id, event.node)
        }
    }
    // 展开
    expandAll(rs) {
        for (const node of rs) {
            this.TreeExpandRecursive(node, true);
        }
    }
    private TreeExpandRecursive(node: TreeNode, isExpand: boolean) {
        node.expanded = isExpand;
        if (node.children) {
            node.children.forEach((childNode) => {
                this.TreeExpandRecursive(childNode, isExpand);
            });
        }
    }
    /**点击树节点展示节点信息
     * nodeId
     * bopDescId
     * sorting
     * maxResultCount
     * skipCount
     */
    getNodePlanDetails(nodeId, event?: LazyLoadEvent): void {
        // if (this.primengTableHelper.shouldResetPaging(event)) {
        //   this.paginator.changePage(0);
        //   return;
        // }
        abp.ui.setBusy();
        this.nodeDataArray = []
        this.linkDataArray = []
        this.tableList = []
        let inp = new PartsOutboundInput()
        inp.nodeId = nodeId
        this._matingManagerServiceProxy.displayMatingNodeDetails(
            inp
        )
            .pipe(finalize(() => { }))
            .subscribe(result => {
                abp.ui.clearBusy();
                this.tableList = result;
                this.expandAll(this.tableList.matingTreeGridList);
                this.diagram.initialContentAlignment = go.Spot.Center;
                this.diagram.grid.visible = true; // 画布上面是否出现网格
                this.diagram.grid.gridCellSize = new go.Size(10, 10);
                this.diagram.nodeTemplateMap.add(
                    "Process",
                    this.goGo(
                        go.Node,
                        "Auto",
                        {
                            locationSpot: new go.Spot(0.5, 0.5),
                            locationObjectName: "SHAPE",
                            resizable: true,
                            resizeObjectName: "SHAPE",
                        },
                        new go.Binding("location", "loc", go.Point.parse).makeTwoWay(
                            go.Point.stringify
                        ),
                        this.goGo(
                            go.Shape,
                            "RoundedRectangle",
                            {
                                name: "SHAPE",
                                strokeWidth: 2,
                            },
                            {
                                click: function (e, obj) {
                                },
                            },
                            new go.Binding("fill"),
                            new go.Binding("desiredSize", "size", go.Size.parse).makeTwoWay(
                                go.Size.stringify
                            )
                        ),

                        this.goGo(
                            go.TextBlock,
                            {
                                alignment: go.Spot.Center,
                                textAlign: "center",
                                margin: 5,
                                editable: true,
                            },
                            new go.Binding("text").makeTwoWay()
                        )
                    )
                );
                this.diagram.linkTemplateMap.add(
                    "noGj",
                    this.goGo(
                        go.Link,
                        this.goGo(go.Shape, {
                            strokeWidth: 2,
                        })
                    )
                );
                this.processNodeList = [];
                this.nodeDataArray = [];
                this.linkDataArray = [];
                this.processNodeList = result.processNodeList
                result.processNodeList.forEach(item => {
                    let itemI = {
                        key: item.key,
                        category: "Process",
                        loc: item.loc,
                        text: item.text,
                        fill: item.fill,
                        color:item.color
                    }
                    this.nodeDataArray.push(itemI)
                })
                result.processLineList.forEach(line => {
                    let itemLine = {
                        from: line.from,
                        to: line.to
                    }
                    this.linkDataArray.push(itemLine)
                })
                this.diagram.model = new go.GraphLinksModel(
                    this.nodeDataArray,
                    this.linkDataArray
                );
            });
    }

    // 加载工序工步节点 
    getProductionTechquine(nodeId, node) {
        this._productionDesignServiceProxy.getProductionTechquine(
            nodeId
        )
            .pipe(finalize(() => { }))
            .subscribe(result => {
                let childNodes = this.isEqual(JSON.parse(JSON.stringify(result)))
                node.children = childNodes
                node.treeList = childNodes
            });
    }
    /** 默认排配计划
     * nodeId!: string | undefined; 当前点击节点id
     * bopDescId!: string | undefined; 任务id 
     * startTime!: moment.Moment | undefined; 开始日期
     * endTime!: moment.Moment | undefined; 结束日期
     * nodeDesc!: string | undefined; 节点描述
     */
    getDefaultArrangement() {
        if (!this.selectedFiles1) {
            this._messageService.warn("请先选择一个节点")
            return
        }
        if (this.selectedFiles1.treeList.length == 0) {
            this._messageService.warn("当前节点下无数据")
            return
        }
        this.defaultInfo.bopDescId = this.files2[0].id
        this.defaultInfo.nodeId = this.selectedFiles1.id
        this.defaultInfo.nodeDesc = this.selectedFiles1.nodeName
        this._productionDesignServiceProxy.defaultArrangement(
            this.defaultInfo
        )
            .pipe(finalize(() => { }))
            .subscribe(result => {
                this.defaultVisible = false
                this._messageService.success("成功")
            });
    }

    // 导出配套表
    handManage() {
        this._messageService.confirm(
            '确定导出配套列表？',
            (isConfirmed) => {
                if (isConfirmed) {
                    this._matingManagerServiceProxy.getBomMatingToExcelById(
                        this.selectNode.id
                    )
                        .pipe(finalize(() => { }))
                        .subscribe(result => {
                            // this.saveFlag = true;
                            // this._fileDownloadService.downloadTempFile(result);
                            window.open(result);
                            URL.revokeObjectURL(result);
                            this.getDesigenTree()
                        });
                }
            }
        );
        // }

    }
    // 取消配套
    taskIssue() {
        if (this.selectRow.length === 0) {
            this._messageService.warn("请选择要解套的列表")
            return
        }
        let parentArr = []
        for (let index = 0; index < this.selectRow.length; index++) {
            const element = this.selectRow[index];
            if (!element.children || element.data.nodeLevel == 10) {
                let dto = new MatingTreeGridDto()
                dto.children = [],
                    dto.data = element.data
                parentArr.push(dto)
            }
        }
        if (this.saveFlag) {
            this.saveFlag = false;
            this._messageService.confirm(
                '确定解套选中数据？',
                (isConfirmed) => {
                    if (isConfirmed) {
                        this._matingManagerServiceProxy.relieveMating(
                            parentArr
                        )
                            .pipe(finalize(() => { }))
                            .subscribe(result => {
                                this.saveFlag = true;
                                if (result.code == 0) {
                                    this.selectRow = []
                                    this._messageService.success("解套成功")
                                    this.getNodePlanDetails(this.selectNode.id)
                                } else {
                                    this._messageService.error(result.message)
                                }
                            });
                    }
                }
            );
        }
    }
    //履历
    llVisibleEv(id) {
        this.llVisible = true
        this._operationHistoryServiceProxy.getOperationLogList(
            id
        )
            .pipe(finalize(() => { }))
            .subscribe(result => {
                this.logList = result
            });
    }
    //人工预配套信息
    getExecutePreSuitePersonEv(car, type) {
        this.dialogType = type
        this.detailInfo.info = car
        this._matingManagerServiceProxy.getExecuteMatingPreSuitePerson(
            car.node.data.storeStockId, car.node.data.workStepId, car.node.data.loadDetailsId, car.node.data.collectId
        )
            .pipe(finalize(() => { }))
            .subscribe(result => {
                this.detailInfo.list = result
                this.rengongSelect = result.filter(item => {
                    return item.isSuit == 1
                })
                this.detailVisible = true
            });
    }
    // 人工预配套配套和取消预配套
    executePreSuitePersonEv() {
        let info: any
        this.detailInfo.info.node.data.storeContents = this.rengongSelect
        info = this.detailInfo.info.node.data
        if (this.saveFlag) {
            this.saveFlag = false;
            this._matingManagerServiceProxy.completePerson(
                info
            )
                .pipe(finalize(() => { }))
                .subscribe(result => {
                    this.saveFlag = true;
                    if (result.code == 0) {
                        this.detailVisible = false
                        this.getNodePlanDetails(this.selectNode.id)
                        this._messageService.success('操作成功');
                    } else {
                        this._messageService.error(result.message)
                    }
                });
        }
    }
    // 修改
    upatePlanEv() {
        let flag: any = this.addInfoUi.renovateFlag
        flag == "1" ? this.addInfoUi.renovateFlag = true : this.addInfoUi.renovateFlag = false
        let organizationUnitId: any = this.addInfoUi.organizationUnitId
        let userId: any = this.addInfoUi.userId
        let idStr = "", unitIdStr = "";
        userId.forEach(element => {
            idStr += `${element.id},`
        });
        organizationUnitId.forEach(element => {
            unitIdStr += `${element.id},`
        });
        this.addInfoUi.userId = idStr
        this.addInfoUi.organizationUnitId = unitIdStr
        if (this.saveFlag) {
            this.saveFlag = false;
            this._messageService.confirm(
                '确定修改数据？',
                (isConfirmed) => {
                    if (isConfirmed) {
                        this._productionDesignServiceProxy.upatePlan(
                            this.addInfoUi
                        )
                            .pipe(finalize(() => { }))
                            .subscribe(result => {
                                this.saveFlag = true;
                                if (result.code == 0) {
                                    this.addVisible = false
                                    this._messageService.success("修改成功")
                                } else {
                                    this._messageService.error(result.message)
                                }
                            });
                    }
                }
            );
        }
    }
    // 配套
    handelEv() {
        if (this.selectRow.length === 0) {
            this._messageService.warn("请选择要配套的列表")
            return
        }

        this._messageService.confirm(
            '确定配套选中数据？',
            (isConfirmed) => {
                if (isConfirmed) {
                    // 提取不同的父节点
                    let parentArr = []
                    for (let index = 0; index < this.selectRow.length; index++) {
                        const element = this.selectRow[index];
                        if (!element.children || element.data.nodeLevel == 10) {
                            let dto = new MatingTreeGridDto()
                            dto.children = [],
                                dto.data = element.data
                            parentArr.push(dto)
                        }
                    }
                    if (this.saveFlag) {
                        this.saveFlag = false;
                        this._matingManagerServiceProxy.matingExecute(
                            parentArr,
                        )
                            .pipe(finalize(() => { }))
                            .subscribe(result => {
                                this.saveFlag = true;
                                if (result.code == 0) {
                                    this.selectRow = []
                                    this._messageService.success("配套成功")
                                    // this.getDesigenTree()
                                    this.getNodePlanDetails(this.selectNode.id)
                                } else {
                                    this._messageService.error(result.message)
                                }


                            });
                    }

                }
            }
        );
    }
    //弹窗隐藏
    displayclose(): void {
        this.addInfoUi = new HandManageInput();//新增集合
        this.defaultInfo = new DefaultArrangementInput()
        this.handelInfo = new HandManageInput();
    }

}
